package com.controller;

import com.model.PaymentModel;
import com.services.IPaymentServices;
import com.services.impl.PaymentServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/payments")
public class PaymentController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        Map<String, Object> result = new HashMap<>();
        
        try {
            // 读取请求体
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            // 解析JSON数据
            JSONObject jsonData = JSONObject.fromObject(sb.toString());
            
            // 创建支付对象
            PaymentModel payment = new PaymentModel();
            payment.setOrderId(jsonData.getInt("orderId"));
            payment.setPaymentMethod(jsonData.getString("paymentMethod"));
            payment.setAmount(new BigDecimal(jsonData.getString("amount")));
            
            if (jsonData.has("cardInfo")) {
                payment.setCardInfo(jsonData.getJSONObject("cardInfo").toString());
            }
            
            // 处理支付
            IPaymentServices paymentServices = new PaymentServicesImpl();
            PaymentModel createdPayment = paymentServices.createPayment(payment);
            
            result.put("code", 0);
            result.put("msg", "支付成功");
            result.put("data", createdPayment);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "支付失败：" + e.getMessage());
        }
        
        response.getWriter().write(JSONObject.fromObject(result).toString());
    }
} 